﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using System.Web;
using umbraco.cms.businesslogic.member;

namespace Designit.Umb.Newsletter.Bll
{
    public class Helper
    {

        /// <summary>
        /// Gets the current host URL.
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentHostUrl()
        {
            //var currentDomain = HttpContext.Current.Request.Url.Host;
            //if (HttpContext.Current.Request.Url.Port != 80)
            //    currentDomain += string.Format(":{0}", HttpContext.Current.Request.Url.Port);
            //if (!currentDomain.StartsWith("http://") || !currentDomain.StartsWith("https"))
            //    currentDomain = string.Format("http://{0}", currentDomain);
            //return currentDomain;
            var currentDomain = MailSettings.Get().Domain;
            if (!currentDomain.StartsWith("http://") || !currentDomain.StartsWith("https"))
                currentDomain = string.Format("http://{0}", currentDomain);
            return currentDomain;
        }

        public static string InsertHostIntoLink(string content)
        {
            var regex = @"href=""/";
            var server = GetCurrentHostUrl();
            foreach (var match in Regex.Matches(content, regex, RegexOptions.IgnoreCase))
            {
                content = Regex.Replace(content, regex, "href=\"" + server + "/");
            }

            regex = @"url=""/";
            foreach (var match in Regex.Matches(content, regex, RegexOptions.IgnoreCase))
            {
                content = Regex.Replace(content, regex, "url=\"" + server + "/");
            }

            regex = @"src=""/";
            foreach (var match in Regex.Matches(content, regex, RegexOptions.IgnoreCase))
            {
                content = Regex.Replace(content, regex, "src=\"" + server + "/");
            }

            return content;
        }

        /// <summary>
        /// Returns a sorted array of list items. All the time zones about which information is available on the local system.
        /// </summary>
        /// <param name="selectedTimezoneId">The selected timezone id.</param>
        /// <returns></returns>
        public static ListItem[] GetTimezoneListItems(string selectedTimezoneId)
        {
            var ret = new ListItem[TimeZoneInfo.GetSystemTimeZones().Count];
            var i = 0;
            foreach (var timeZoneInfo in TimeZoneInfo.GetSystemTimeZones())
            {
                var li = new ListItem(timeZoneInfo.DisplayName, timeZoneInfo.Id);
                if (timeZoneInfo.Id == selectedTimezoneId)
                    li.Selected = true;
                ret[i] = li;
                i++;
            }
            return ret;
        }

        /// <summary>
        /// Gets the template dir.
        /// </summary>
        /// <returns></returns>
        public static string GetTemplateDir()
        {
            var path = "/designit/newsletter/masterpages";
            path = HttpContext.Current.Server.MapPath(path);
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            return path;
        }

        /// <summary>
        /// Gets the members for campaign.
        /// </summary>
        /// <param name="campaignId">The campaign id.</param>
        /// <returns></returns>
        public static List<Member> GetMembersForCampaign(int campaignId)
        {
            var ret = new List<Member>();
            var bounceGroup = MemberGroup.GetByName("Bounced");

            using (var reader = umbraco.BusinessLogic.Application.SqlHelper.ExecuteReader("SELECT * FROM newsLetterCampaign2Group WHERE campaignId = @campaignId",
               umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campaignId", campaignId)))
            {
                while (reader.Read())
                {
                    foreach (var member in MemberGroup.GetByName(reader.GetString("groupName")).GetMembers())
                    {
                        if (!ret.Contains(member))
                        {
                            if(!bounceGroup.HasMember(member.Id))
                                ret.Add(member);
                        }
                    }
                }
            }

            return ret;
        }

        public static int GetNumberOfMembersSentTo(int campaignId)
        {
           return umbraco.BusinessLogic.Application.SqlHelper.ExecuteScalar<int>(
                                "SELECT count(id) FROM newsLetterSendMail WHERE campaignId = @campaignId AND send = 'true'",
                                umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campaignId", campaignId));
        }

        public static string GetStatusText(string status)
        {
            switch (status.ToLower())
            {
                case "delayed":
                    return "Scheduled";
                default:
                    return status;
            }
        }

        public static string AjaxStatus(int campaignId)
        {
            var numSent = GetNumberOfMembersSentTo(campaignId);
            var status = umbraco.BusinessLogic.Application.SqlHelper.ExecuteScalar<string>(
                "SELECT campstatus FROM newsLetterCampaignNewsletter WHERE id = @campaignId",
                umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campaignId", campaignId)
                );
            var statusText = GetStatusText(status);

            var sb = new StringBuilder();
            sb.Append("{");
            sb.AppendFormat("\"{0}\":\"{1}\"", "SentTo", numSent);
            sb.AppendFormat(",\"{0}\":\"{1}\"", "Status", status);
            sb.AppendFormat(",\"{0}\":\"{1}\"", "StatusText", statusText);
            sb.Append("}");
            return sb.ToString();
        }
    }
}
